using System.Collections.Generic;
using System.Linq;
using System.Windows;
using WPF_MVVM_Test.MVVM_ViewModel.WorkOrderTask;

namespace WPF_MVVM_Test.MVVM_View.WorkOrderTask
{
    /// <summary>
    /// EmployeeSelectionDialog.xaml 的交互逻辑
    /// </summary>
    public partial class EmployeeSelectionDialog : Window
    {
        private EmployeeSelectionViewModel _viewModel;

        public bool IsConfirmed { get; private set; }
        public List<string> SelectedEmployeeNames { get; private set; }

        public EmployeeSelectionDialog()
        {
            InitializeComponent();

            _viewModel = new EmployeeSelectionViewModel();
            DataContext = _viewModel;

            // 订阅ViewModel的关闭事件
            _viewModel.RequestClose += OnRequestClose;
        }

        private void OnRequestClose(bool result)
        {
            IsConfirmed = result;

            System.Diagnostics.Debug.WriteLine($"EmployeeSelectionDialog OnRequestClose: result={result}");
            System.Diagnostics.Debug.WriteLine($"SelectedEmployees count: {_viewModel.SelectedEmployees?.Count ?? 0}");

            if (result)
            {
                // 获取选中的员工名称
                SelectedEmployeeNames = _viewModel.SelectedEmployees?.Select(e => e.Name).ToList() ?? new List<string>();
                System.Diagnostics.Debug.WriteLine($"SelectedEmployeeNames count: {SelectedEmployeeNames.Count}");
                System.Diagnostics.Debug.WriteLine($"SelectedEmployeeNames: {string.Join(", ", SelectedEmployeeNames)}");
            }

            DialogResult = result;
            Close();
        }

        protected override void OnClosed(System.EventArgs e)
        {
            // 取消订阅事件
            if (_viewModel != null)
            {
                _viewModel.RequestClose -= OnRequestClose;
            }
            base.OnClosed(e);
        }
    }
}
